<template>
  <div class="roles-container">
    <div class="header">
      <h2>角色管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增角色
      </el-button>
    </div>

    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="searchForm.code" placeholder="请输入角色编码" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.isActive" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="tableData" v-loading="loading" stripe>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="角色名称" />
      <el-table-column prop="code" label="角色编码" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="isActive" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isActive ? 'success' : 'danger'">
            {{ row.isActive ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="warning" size="small" @click="handlePermissions(row)">
            权限配置
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 角色表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        @submit.prevent
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-radio-group v-model="form.isActive">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 权限配置对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="权限配置" width="800px">
      <div class="permission-tree">
        <el-tree
          ref="permissionTreeRef"
          :data="permissionTree"
          :props="treeProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedPermissions"
          @check="handlePermissionCheck"
        />
      </div>
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePermissions" :loading="savingPermissions">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type ElTree } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { Role, Permission } from '@/types/auth'

/**
 * 搜索表单数据
 */
const searchForm = reactive({
  name: '',
  code: '',
  isActive: undefined as boolean | undefined
})

/**
 * 表格数据
 */
const tableData = ref<Role[]>([])
const loading = ref(false)

/**
 * 分页数据
 */
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

/**
 * 对话框相关
 */
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitting = ref(false)

/**
 * 表单数据
 */
const form = reactive({
  id: null as number | null,
  name: '',
  code: '',
  description: '',
  isActive: true
})

/**
 * 表单验证规则
 */
const rules = {
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
  isActive: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

/**
 * 表单引用
 */
const formRef = ref<FormInstance>()

/**
 * 权限配置相关
 */
const permissionDialogVisible = ref(false)
const currentRole = ref<Role | null>(null)
const permissionTree = ref<Permission[]>([])
const checkedPermissions = ref<number[]>([])
const savingPermissions = ref(false)
const permissionTreeRef = ref<InstanceType<typeof ElTree>>()

/**
 * 权限树配置
 */
const treeProps = {
  children: 'children',
  label: 'name'
}

/**
 * 格式化日期
 */
const formatDate = (date: string) => {
  return new Date(date).toLocaleString()
}

/**
 * 获取角色列表
 */
const fetchRoles = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取角色列表
    // const response = await request.get('/api/roles', {
    //   params: {
    //     page: pagination.page,
    //     size: pagination.size,
    //     ...searchForm
    //   }
    // })
    // tableData.value = response.data.data
    // pagination.total = response.data.total
    
    // 模拟数据
    tableData.value = [
      {
        id: 1,
        name: '超级管理员',
        code: 'admin',
        description: '系统超级管理员，拥有所有权限',
        isActive: true,
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: '2024-01-01T00:00:00Z'
      },
      {
        id: 2,
        name: '普通用户',
        code: 'user',
        description: '普通用户，拥有基础权限',
        isActive: true,
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: '2024-01-01T00:00:00Z'
      }
    ]
    pagination.total = 2
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 获取权限树
 */
const fetchPermissionTree = async () => {
  try {
    // TODO: 调用API获取权限树
    // const response = await request.get('/api/permissions/tree')
    // permissionTree.value = response.data
    
    // 模拟数据
    permissionTree.value = [
      {
        id: 1,
        name: '用户管理',
        code: 'user',
        type: 'menu',
        resource: 'user',
        action: 'manage',
        isActive: true,
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: '2024-01-01T00:00:00Z',
        children: [
          { 
            id: 11, 
            name: '查看用户', 
            code: 'user:view', 
            type: 'action',
            resource: 'user',
            action: 'view',
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-01-01T00:00:00Z'
          },
          { 
            id: 12, 
            name: '创建用户', 
            code: 'user:create', 
            type: 'action',
            resource: 'user',
            action: 'create',
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-01-01T00:00:00Z'
          },
          { 
            id: 13, 
            name: '编辑用户', 
            code: 'user:edit', 
            type: 'action',
            resource: 'user',
            action: 'edit',
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-01-01T00:00:00Z'
          },
          { 
            id: 14, 
            name: '删除用户', 
            code: 'user:delete', 
            type: 'action',
            resource: 'user',
            action: 'delete',
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-01-01T00:00:00Z'
          }
        ]
      },
      {
        id: 2,
        name: '角色管理',
        code: 'role',
        type: 'menu',
        resource: 'role',
        action: 'manage',
        isActive: true,
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: '2024-01-01T00:00:00Z',
        children: [
          { 
            id: 21, 
            name: '查看角色', 
            code: 'role:view', 
            type: 'action',
            resource: 'role',
            action: 'view',
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-01-01T00:00:00Z'
          },
          { 
            id: 22, 
            name: '创建角色', 
            code: 'role:create', 
            type: 'action',
            resource: 'role',
            action: 'create',
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-01-01T00:00:00Z'
          },
          { 
            id: 23, 
            name: '编辑角色', 
            code: 'role:edit', 
            type: 'action',
            resource: 'role',
            action: 'edit',
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-01-01T00:00:00Z'
          },
          { 
            id: 24, 
            name: '删除角色', 
            code: 'role:delete', 
            type: 'action',
            resource: 'role',
            action: 'delete',
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-01-01T00:00:00Z'
          }
        ]
      }
    ]
  } catch (error) {
    ElMessage.error('获取权限树失败')
  }
}

/**
 * 搜索
 */
const handleSearch = () => {
  pagination.page = 1
  fetchRoles()
}

/**
 * 重置搜索
 */
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    code: '',
    isActive: undefined
  })
  pagination.page = 1
  fetchRoles()
}

/**
 * 分页大小改变
 */
const handleSizeChange = (size: number) => {
  pagination.size = size
  fetchRoles()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchRoles()
}

/**
 * 新增角色
 */
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  Object.assign(form, {
    id: null,
    name: '',
    code: '',
    description: '',
    isActive: true
  })
  dialogVisible.value = true
}

/**
 * 编辑角色
 */
const handleEdit = (row: Role) => {
  dialogTitle.value = '编辑角色'
  Object.assign(form, {
    id: row.id,
    name: row.name,
    code: row.code,
    description: row.description || '',
    isActive: row.isActive
  })
  dialogVisible.value = true
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // TODO: 调用API保存角色
    // if (form.id) {
    //   await request.put(`/api/roles/${form.id}`, form)
    //   ElMessage.success('更新角色成功')
    // } else {
    //   await request.post('/api/roles', form)
    //   ElMessage.success('创建角色成功')
    // }
    
    ElMessage.success(form.id ? '更新角色成功' : '创建角色成功')
    dialogVisible.value = false
    fetchRoles()
  } catch (error) {
    ElMessage.error('保存角色失败')
  } finally {
    submitting.value = false
  }
}

/**
 * 权限配置
 */
const handlePermissions = async (row: Role) => {
  currentRole.value = row
  
  // 获取角色的权限
  try {
    // TODO: 调用API获取角色权限
    // const response = await request.get(`/api/roles/${row.id}/permissions`)
    // checkedPermissions.value = response.data.map((p: Permission) => p.id)
    
    // 模拟数据
    checkedPermissions.value = [11, 12, 21, 22]
  } catch (error) {
    ElMessage.error('获取角色权限失败')
  }
  
  permissionDialogVisible.value = true
}

/**
 * 权限选择改变
 */
const handlePermissionCheck = () => {
  // 权限选择逻辑可以在这里处理
}

/**
 * 保存权限配置
 */
const handleSavePermissions = async () => {
  if (!currentRole.value || !permissionTreeRef.value) return
  
  try {
    savingPermissions.value = true
    // const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    // const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
    // const _allPermissions = [...checkedKeys, ...halfCheckedKeys]
    
    // TODO: 调用API保存角色权限
    // await request.post(`/api/roles/${currentRole.value.id}/permissions`, {
    //   permissionIds: allPermissions
    // })
    
    ElMessage.success('保存权限配置成功')
    permissionDialogVisible.value = false
  } catch (error) {
    ElMessage.error('保存权限配置失败')
  } finally {
    savingPermissions.value = false
  }
}

/**
 * 删除角色
 */
const handleDelete = async (_row: Role) => {
  try {
    await ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // TODO: 调用API删除角色
    // await request.delete(`/api/roles/${row.id}`)
    
    ElMessage.success('删除角色成功')
    fetchRoles()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除角色失败')
    }
  }
}

onMounted(() => {
  fetchRoles()
  fetchPermissionTree()
})
</script>

<style scoped>
.roles-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.search-form {
  margin: 0;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.permission-tree {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}
</style>